<?php

namespace Shop\AdminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Shop\AdminBundle\Controller\BaseController;

//use Shop\AdminBundle\Entity\AdminRole;
use Shop\AdminBundle\Entity\AdminUser;

//use Shop\AdminBundle\Form\AdminRoleType;
use Shop\AdminBundle\Form\AdminUserType;

/**
 * AdminUser controller.
 *
 * @Route("/admin/admin_user")
 */
class AdminUserController extends BaseController
{
    /**
     * 后台用户列表，页面
     *
     * @Route("/", name="adminuser")
     * @Method("GET")
     * @Template("ShopAdminBundle:AdminUser:index.html.twig")
     */
    public function indexAction()
    {
        $repo=$this->getRepo('adminUser');
        $viewData=$this->paginate($repo);
        //get role list
        $roleList=$this->getRoleList();
        if(!empty($roleList)){
            $ret=[];
            foreach($roleList as $role){
                $ret[$role['id']]=$role['rolename'];
            }
            $roleList=$ret;
        }
        return array_merge($viewData, ['roleList'=>$roleList]);
    }

    protected function getRoleList(){
        /**@var \Shop\AdminBundle\Entity\AdminRoleRepository $roleRepo */
        $roleRepo=$this->getRepo('adminRole');
        $userRoleList=$roleRepo->getRoleList();
        return $userRoleList;
    }

    /**
     * 创建后台用户
     *
     * @Route("/new", name="adminuser_new")
     * @Method("GET")
     * @Template("ShopAdminBundle:AdminUser:new.html.twig")
     */
    public function newAction()
    {
        $entity = new AdminUser();
        $form = $this->createForm(new AdminUserType(), $entity, array(
            'action' => $this->generateUrl('adminuser_create'),
            'method' => 'POST',
        ));

        $userRoleList=$this->getRoleList();

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
            'roleList'=>$userRoleList,
            'ajax_form'=>true
        );
    }

    /**
     * 创建后台用户，表单处理
     *
     * @Route("/", name="adminuser_create")
     * @Method("POST")
     */
    public function createAction(Request $request)
    {
        $entity = new AdminUser();
        $form = $this->createForm(new AdminUserType(), $entity, array(
            'action' => $this->generateUrl('adminuser_create'),
            'method' => 'POST',
        ));
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            //gen salt
            $now=time();
            $entity->setCtime($now);
            $salt=substr( md5($entity->getCtime()), 0, 10 );
            $entity->setSalt($salt);
            $entity->setPassword( md5($salt. $entity->getPassword()) );
            $entity->setLastLogin(0);
            $entity->setCountLogin(0);

            $em->persist($entity);
            $em->flush();
            return $this->redirect($this->generateUrl('adminuser') );
        }

        return $this->redirect($this->generateUrl('adminuser_new') );

    }

    /**
     * 编辑后台用户，页面
     *
     * @Route("/{id}/edit", name="adminuser_edit")
     * @Method("GET")
     * @Template("ShopAdminBundle:AdminUser:new.html.twig")
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ShopAdminBundle:AdminUser')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find AdminUser entity.');
        }

        $editForm = $this->createForm(new AdminUserType(), $entity, array(
            'action' => $this->generateUrl('adminuser_update',
                array('id' => $entity->getId())),
            'method' => 'POST',
        ));

        $userRoleList=$this->getRoleList();
//        dump($userRoleList);exit;

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'roleList'=>$userRoleList,
            'is_edit'=>true,
            'ajax_form'=>true
        );
    }

    /**
     * 更新后台用户，表单处理
     *
     * @Route("/{id}", name="adminuser_update")
     * @Method("POST")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ShopAdminBundle:AdminUser')->find($id);

        $origSalt=$entity->getSalt();
        $origPassword=$entity->getPassword();
        $origLastLogin=$entity->getLastLogin();
        $origCountLogin=$entity->getCountLogin();
        $origCtime=$entity->getCtime();

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find AdminUser entity.');
        }

        $editForm = $this->createForm(new AdminUserType(), $entity, array(
            'action' => $this->generateUrl('adminuser_update',
                array('id' => $entity->getId())),
            'method' => 'POST',
        ));

        $editForm->handleRequest($request);

        if ($editForm->isValid()) {

            if(!empty($entity->getPassword())){
                $entity->setPassword( md5($origSalt.$entity->getPassword()) );
            }
            else{
                $entity->setPassword( $origPassword );
            }
            $entity->setUsername($entity->getUsername());
            $entity->setRoleId($entity->getRoleId());

            //restore
            $entity->setSalt($origSalt);
            $entity->setLastLogin($origLastLogin);
            $entity->setCountLogin($origCountLogin);
            $entity->setCtime($origCtime);

            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('adminuser'));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
        );
    }
    /**
     * 删除后台用户，页面
     *
     * @Route("/{id}/delete", name="adminuser_delete")
     * @Method("GET")
     */
    public function deleteAction(Request $request, $id)
    {
        return $this->deleteRow('adminUser', $request, $id);
    }
}
